using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
namespace Test {
	class RfHeartBeat {
		public DAL dal=new DAL();
		static void MainX() {
			RfHeartBeat b=new RfHeartBeat();
			Ping p=new Ping();
			List<string> lservers=new List<string>();
			lservers.AddRange(Mixer.Combine("pon-wprf0{0}-cl0{1}","1,2,3,4","1,2"));
			lservers.AddRange(Mixer.Combine("pon-wpwb03-cl0{0}","1,2"));
			string[] servers=lservers.ToArray();
			while(true)
			{
				foreach(string server in servers)
				{
					int err;
					TimeSpan ts=b.Send(server,out err);
					PingReply pr=p.Send(server);
					b.dal.NonQry("insert into RfSurvey(srv,val,err,ptime,perr)values('{0}',{1},{2},{3},{4})",server,ts.TotalMilliseconds,err,pr.RoundtripTime,(int)pr.Status);
					System.Threading.Thread.Sleep(500);
				}
			}
		}
		Dictionary<string,int> failures=new Dictionary<string,int>();
		byte[] sendBuffer=Encoding.ASCII.GetBytes("0000000000000");
		byte[] _rcvBuffer=new byte[8192];
		EndPoint rcvEP=new IPEndPoint(IPAddress.Any,0);
		TimeSpan Send(string server,out int err) {
			//Console.Write(server);
			//Console.Write(": ");
			using(Socket sndSocket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp))
			{
				err=0;
				try
				{
					EndPoint sndEP=new IPEndPoint(Dns.GetHostAddresses(server)[0],20000);
					sndSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,700);
					int sent=sndSocket.SendTo(sendBuffer,sndEP);
					int rcvCount=0;
					System.Diagnostics.Stopwatch sw=System.Diagnostics.Stopwatch.StartNew();
					try
					{
						rcvCount=sndSocket.ReceiveFrom(_rcvBuffer,ref rcvEP);
					}
					catch(Exception exception)
					{
						if(exception is SocketException)
						{
							err=(exception as SocketException).ErrorCode;
						}
						if(failures.ContainsKey(server))
							failures[server]++;
						else
							failures.Add(server,1);
						Console.Write(DateTime.Now.ToString("HH:mm:ss - ")+server+" - "+exception.Message+" ");
						Console.WriteLine();
						//sndSocket.SendTo(sendBuffer,sndEP);
						//rcvCount=sndSocket.ReceiveFrom(_rcvBuffer,ref rcvEP);
					}
					return sw.Elapsed;
					//Console.WriteLine(sw.Elapsed);
					//Console.WriteLine();
					//string str=Encoding.ASCII.GetString(_rcvBuffer);
					//bool nl=false;
					//foreach(char ch in str)
					//  if(char.IsLetterOrDigit(ch)||ch==' '||ch=='/'||ch==':'||ch=='\'')
					//  {
					//    Console.Write(ch);
					//    nl=false;
					//  }
					//  else if(!nl)
					//  {
					//    Console.WriteLine();
					//    nl=true;
					//  }
				}
				finally
				{
					sndSocket.Shutdown(SocketShutdown.Both);
					sndSocket.Close();
				}
			}
		}
	}
}
